package com.thp.bigdata.zkdst;

import java.io.IOException;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

/**
 * 分布式系统的服务端
 * @author tommy
 *
 */
public class DistributeServer {

	
	
	private static final String connectString = "bd1:2181,bd2:2181,bd3:2181";
	// 超时时间
	private static final int sessionTimeout = 2000;
	
	private static final String parentNode = "/servers";
	
	
	
	private ZooKeeper zk = null;
	
	
	/**
	 * 创建到zk的客户端连接
	 * @throws IOException
	 */
	public void getConnect() throws IOException {
		zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
			@Override
			public void process(WatchedEvent event) {
				// 收到事件通知后的回调函数 (应该是我们自己的事件处理逻辑)
				System.out.println(event.getType() + " -- " + event.getPath()); // 事件的类型  --   事件发生的节点
				try {
					// getChildren 只是为了 设置这个监听  相当于又监听了
					zk.getChildren("/", true);
				} catch (KeeperException | InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	
	
	/**
	 * 判断节点是否存在
	 * @param node
	 * @return
	 * @throws KeeperException
	 * @throws InterruptedException
	 */
	public boolean isExist(String node) throws KeeperException, InterruptedException {
		Stat stat = zk.exists(node, false);
		return stat == null ? false : true;
	}
	
	/**
	 * 创建节点
	 * @param node
	 * @throws KeeperException
	 * @throws InterruptedException
	 */
	public void createNode(String node) throws KeeperException, InterruptedException {
		zk.create(node, "server-node".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
	}

	/**
	 * 向zk集群注册服务器信息
	 * @param hostname
	 * @throws KeeperException
	 * @throws InterruptedException
	 */
	public void registerServer(String hostname) throws KeeperException, InterruptedException {
		if(!isExist(parentNode)) {  // 父节点不存在则创建节点
			createNode(parentNode);
		}
		
		// 节点类型是临时的带序号的   这样可以保证不会冲突
		String create = zk.create(parentNode + "/server", hostname.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
		System.out.println(hostname + "is online..." + create);
	}
	
	
	
	/**
	 * 业务功能
	 * @throws InterruptedException 
	 */
	public void handleBussiness(String hostname) throws InterruptedException {
		System.out.println(hostname + "is working...");
		Thread.sleep(Long.MAX_VALUE);
	}
	
	
	public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
		// 1.获取zk连接  
		DistributeServer server = new DistributeServer();
		server.getConnect();
		// 2.利用zk连接注册服务器信息
		server.registerServer(args[0]);
		// 3.启动业务功能
		server.handleBussiness(args[0]);
	}
	
	
}
